import * as THREE from 'three'
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer'
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass'
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass'

export class RendererManager {
  private renderer: THREE.WebGLRenderer
  private composer: EffectComposer
  private bloomPass: UnrealBloomPass
  private renderPass: RenderPass

  constructor() {
    // 创建渲染器
    this.renderer = new THREE.WebGLRenderer({
      antialias: true,
      alpha: true
    })
    this.renderer.setPixelRatio(window.devicePixelRatio)
    this.renderer.setSize(window.innerWidth, window.innerHeight)
    this.renderer.shadowMap.enabled = true
    this.renderer.shadowMap.type = THREE.PCFSoftShadowMap

    // 创建后期处理效果
    this.initPostProcessing()

    // 监听窗口大小变化
    window.addEventListener('resize', this.onWindowResize.bind(this))
  }

  private onWindowResize(): void {
    const width = window.innerWidth
    const height = window.innerHeight

    this.renderer.setSize(width, height)
    this.composer.setSize(width, height)

    if (this.bloomPass) {
      this.bloomPass.resolution.set(width, height)
    }
    // Note: Camera aspect ratio is handled by CameraManager
  }

  private initPostProcessing(): void {
    this.renderPass = new RenderPass()
    this.bloomPass = new UnrealBloomPass(
      new THREE.Vector2(window.innerWidth, window.innerHeight),
      1.5, // 强度
      0.4, // 半径
      0.85 // 阈值
    )

    this.composer = new EffectComposer(this.renderer)
    this.composer.addPass(this.renderPass)
    this.composer.addPass(this.bloomPass)
  }

  public setBloomEnabled(enabled: boolean): void {
    this.bloomPass.enabled = enabled
  }

  public setBloomStrength(strength: number): void {
    this.bloomPass.strength = strength
  }

  public setBloomRadius(radius: number): void {
    this.bloomPass.radius = radius
  }

  public setBloomThreshold(threshold: number): void {
    this.bloomPass.threshold = threshold
  }

  public render(scene: THREE.Scene, camera: THREE.Camera): void {
    // 更新渲染通道的场景和相机
    this.renderPass.scene = scene
    this.renderPass.camera = camera

    // 使用后期处理效果进行渲染
    this.composer.render()
  }

  public getRenderer(): THREE.WebGLRenderer {
    return this.renderer
  }

  public getComposer(): EffectComposer {
    return this.composer
  }

  public dispose(): void {
    window.removeEventListener('resize', this.onWindowResize.bind(this))
    // Add any other disposal logic for renderer and composer if needed
  }
}
